package cn.dujc.superkid.api;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.dujc.superkid.BuildConfig;
import cn.dujc.superkid.configs.Globals;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by du on 2017/6/15.
 */
public class HttpHelper {

    private static Retrofit sRetrofit = null;
    private static ApiLoginRegister sLoginRegister = null;
    private static ApiUserCenter sUserCenter = null;
    private static ApiHome sHome = null;
    private static ApiCourse sCourse = null;
    private static ApiCupMatch sCupMatch = null;
    private static ApiExamineOnline sExamineOnline = null;
    private static ApiAnswerOnline sAnswerOnline = null;
    private static ApiPayment sPayment = null;

    private HttpHelper() { }

    private static Retrofit getRetrofit() {
        if (sRetrofit == null) {
            synchronized (HttpHelper.class) {
                if (sRetrofit == null) {
                    //CookieJar myCookieStore = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
                    final OkHttpClient.Builder http = new OkHttpClient.Builder();
                    if (BuildConfig.DEBUG) {
                        http.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
                    }
                    //http.cookieJar(myCookieStore);
                    if (Globals.BASE_URL.startsWith("https://")) {
                        setupSSL(http);
                    }
                    final GsonConverterFactory gsonConverterFactory;
                    gsonConverterFactory = GsonConverterFactory.create();
                    /*
                    //这段话与上面的代码二选一即可，这段话注册了一个反序列化类，能避免任何类型错误，但缺点就是
                    //在常规反序列失败的时候，调用的是反射，将所有的字段一一取出赋值，即除类型错误的字段外，其他字段能正常赋值
                    GsonBuilder gson = new GsonBuilder()
                            .registerTypeAdapter(Result.class, new GodDeserializer<Result>());
                    gsonConverterFactory = GsonConverterFactory.create(gson.create());*/
                    sRetrofit = new Retrofit.Builder()
                            .client(http.build())
                            .baseUrl(Globals.BASE_URL)
                            .addConverterFactory(gsonConverterFactory)
                            .build();
                }
            }
        }
        return sRetrofit;
    }

    private static void setupSSL(OkHttpClient.Builder builder) {
        final X509TrustManager manager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        SSLContext context = null;
        try {
            context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{manager}, null);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        if (context != null) {
            builder.sslSocketFactory(context.getSocketFactory(), manager);
        }
    }

    public static ApiLoginRegister getLoginRegister() {
        if (sLoginRegister == null) {
            synchronized (HttpHelper.class) {
                if (sLoginRegister == null) {//双层加锁
                    sLoginRegister = getRetrofit().create(ApiLoginRegister.class);
                }
            }
        }
        return sLoginRegister;
    }

    public static ApiUserCenter getUserCenter() {
        if (sUserCenter == null) {
            synchronized (HttpHelper.class) {
                if (sUserCenter == null) {//双层加锁
                    sUserCenter = getRetrofit().create(ApiUserCenter.class);
                }
            }
        }
        return sUserCenter;
    }

    public static ApiHome getHome() {
        if (sHome == null) {
            synchronized (HttpHelper.class) {
                if (sHome == null) {//双层加锁
                    sHome = getRetrofit().create(ApiHome.class);
                }
            }
        }
        return sHome;
    }

    public static ApiCourse getCourse() {
        if (sCourse == null) {
            synchronized (HttpHelper.class) {
                if (sCourse == null) {//双层加锁
                    sCourse = getRetrofit().create(ApiCourse.class);
                }
            }
        }
        return sCourse;
    }

    public static ApiCupMatch getCupMatch() {
        if (sCupMatch == null) {
            synchronized (HttpHelper.class) {
                if (sCupMatch == null) {//双层加锁
                    sCupMatch = getRetrofit().create(ApiCupMatch.class);
                }
            }
        }
        return sCupMatch;
    }

    public static ApiExamineOnline getExamineOnline() {
        if (sExamineOnline == null) {
            synchronized (HttpHelper.class) {
                if (sExamineOnline == null) {//双层加锁
                    sExamineOnline = getRetrofit().create(ApiExamineOnline.class);
                }
            }
        }
        return sExamineOnline;
    }

    public static ApiAnswerOnline getAnswerOnline() {
        if (sAnswerOnline == null) {
            synchronized (HttpHelper.class) {
                if (sAnswerOnline == null) {//双层加锁
                    sAnswerOnline = getRetrofit().create(ApiAnswerOnline.class);
                }
            }
        }
        return sAnswerOnline;
    }

    public static ApiPayment getPayment() {
        if (sPayment == null) {
            synchronized (HttpHelper.class) {
                if (sPayment == null) {//双层加锁
                    sPayment = getRetrofit().create(ApiPayment.class);
                }
            }
        }
        return sPayment;
    }

}